package com.cash.loan.modular.cash.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.cash.loan.core.upload.QiniuService;
import com.cash.loan.core.util.DateUtil;
import com.cash.loan.modular.cash.dao.LoanProductDetailMapper;
import com.cash.loan.modular.cash.dao.LoanProductMapper;
import com.cash.loan.modular.cash.model.LoanProduct;
import com.cash.loan.modular.cash.model.LoanProductDetail;
import com.cash.loan.modular.cash.result.PageResult;
import com.cash.loan.modular.cash.service.ProductService;
import com.cash.loan.modular.cash.transfer.*;
import com.cash.loan.modular.cash.util.PageBeanUtil;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 *
 * 产品服务实现类
 * @author Administrator
 * @Date 2018-07-11 15:57
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private LoanProductMapper productMapper;

    @Autowired
    private LoanProductDetailMapper productDetailMapper;

    @Autowired
    private QiniuService qiniuService;

    @Override
    public PageResult<ProductListVo> getProductList(Integer currentPage, Integer pageSize, ProductQueryDto queryDto) {

        PageHelper.startPage(currentPage,pageSize);

        List<ProductListVo> productListVoList = productMapper.getProductListByConditions(queryDto);

        List<ProductListStrVo> productListStrVoList = new ArrayList<>();

        productListVoList.stream().forEach(
                productListVo -> {
                    ProductListStrVo productListStrVo = new ProductListStrVo();
                    BeanUtils.copyProperties(productListVo,productListStrVo);
                    productListStrVo.setOnlineDate(DateUtil.format(productListVo.getOnlineDate(),"yyyy-MM-dd"));
                    productListStrVoList.add(productListStrVo);
                }
        );

        PageResult pageResult = PageBeanUtil.toPageResult(productListVoList);

        pageResult.setDataList(productListStrVoList);

        return pageResult;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public Boolean saveProduct(NewProductDto productDto) {

        LoanProduct loanProduct = new LoanProduct();

        LoanProductDetail productDetail = new LoanProductDetail();

        BeanUtils.copyProperties(productDto,loanProduct);

        BeanUtils.copyProperties(productDto,productDetail);

        Long productId = IdWorker.getId();

        loanProduct.setProductId(String.valueOf(productId));

        productDetail.setProductId(String.valueOf(productId));

        String applyFlowList = JSONArray.toJSONString(productDto.getApplyFlowList());

        productDetail.setApplyFlowList(applyFlowList);

        productMapper.insert(loanProduct);

        productDetailMapper.insert(productDetail);

        return true;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public Boolean updateProductStatus(Long productId, Long productFlag) {
        productMapper.updateProductStatus(productId,productFlag);
        return true;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public Boolean updateManageStatus(Long productId, Long manageFlag) {
        productMapper.updateManageStatus(productId,manageFlag);
        return true;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public Boolean updateDownloadStatus(Long productId, Long downloadFlag) {
        productMapper.updateDownloadStatus(productId,downloadFlag);
        return true;
    }

    /**
     * 产品详情
     * @param productId
     * @return
     */
    @Override
    public ProductDetailMapVo productDetail(Long productId) {
        ProductDetailMapVo mapVo = new ProductDetailMapVo();
        ProductDetailVo productDetailVo = productMapper.getProductDetail(productId);

        if(productDetailVo == null) {
            return null;
        }

        BeanUtils.copyProperties(productDetailVo,mapVo);

        JSONArray applyFlowList = JSONArray.parseArray(productDetailVo.getApplyFlowList());

        mapVo.setApplyFlowList(applyFlowList);

        mapVo.setProductIconUrl(qiniuService.getUrl(productDetailVo.getProductIconUrl()));

        return mapVo;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public Boolean updateProductStatus(UpdateProductDto productDto) {

        LoanProduct loanProduct = new LoanProduct();

        LoanProductDetail productDetail = new LoanProductDetail();

        BeanUtils.copyProperties(productDto,loanProduct);

        BeanUtils.copyProperties(productDto,productDetail);
        String productId = productMapper.selectById(loanProduct.getId()).getProductId();
        Long detailId = productDetailMapper.getIdByProductId(productId);
        productDetail.setId(detailId);

        String applyFlowList = JSONArray.toJSONString(productDto.getApplyFlowList());

        productDetail.setApplyFlowList(applyFlowList);

        productMapper.updateById(loanProduct);

        productDetailMapper.updateById(productDetail);

        return true;
    }

    @Override
    public PageResult<Map<String,Object>> listProductPvAndUv(Integer currentPage,Integer pageSize,Long productId) {
        PageHelper.startPage(currentPage,pageSize);
        List<Map<String,Object>> pvList = productMapper.productPv(productId);
        List<Map<String,Object>> result = new ArrayList<>();
        if(pvList.size() >= 1) {
            pvList.stream().forEach(map -> {
                DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                if(map.get("pv") != null && map.get("uv") != null) {
                    map.put("date",format.format((Date) map.get("date")));
                } else {
                    map.put("date",format.format(new Date()));
                    map.put("pv",0);
                    map.put("uv",0);
                }
                result.add(map);
            });
        }
        PageResult<Map<String,Object>> pageResult = PageBeanUtil.toPageResult(pvList);

        pageResult.setDataList(result);

        return pageResult;
    }

    @Override
    public PageResult<Map<String,Object>> getProductListForAd(Integer currentPage, Integer pageSize, String keyword) {

        PageHelper.startPage(currentPage,pageSize);

        List<Map<String,Object>> resultList = productMapper.getProductListForAd(keyword);

        PageResult<Map<String,Object>> pageResult = PageBeanUtil.toPageResult(resultList);

        return pageResult;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public Boolean changeOrderNum(Integer id, Integer orderNum) {
        productMapper.changeOrderNum(id,orderNum);
        return true;
    }

    @Override
    public List<Map<String, Object>> getAllProduct() {
        List<LoanProduct> loanProductList = productMapper.selectList(new EntityWrapper<LoanProduct>());
        List<Map<String,Object>> resultList = new ArrayList<>();
        loanProductList.stream().forEach(loanProduct -> {
            Map<String,Object> map = new HashMap<>(4);
            map.put("id",loanProduct.getId());
            map.put("name",loanProduct.getProductName());
            resultList.add(map);
        });
        return resultList;
    }
}
